<template>
  <div>
    <div class="pusherNetStatus">
      <p>liveMessage:{{liveMessage}}</p>
      <p>liveCode:{{liveCode}}</p>

    </div>
    <live-pusher id='livePusher' ref="livePusher" class="livePusher" :url="pushUrl" :mode="coderate" :beauty="isBeautiful"
                 :whiteness="whitenessLevel" aspect="9:16" @statechange="statechange"
                 @netstatus="netstatus" @error="error"  enable-agc="true" enable-ans="true"
                 :style="{width:pushWidth+'px',height:pushHeight+'px'}"></live-pusher>

  <!--  <scroll-view class="liveSayWrap" scroll-y="true" scroll-with-animation="true" @scroll="scroll" :scroll-into-view="toIndex">
      <div class="tipwrap">
        车队长直播提倡绿色直播，严禁涉政、涉恐、涉黄、聚集闹事、返现等内容，网警24小时巡查。请勿参与直播间非官方奖励活动/游戏，切勿私下交易，以防受骗。
      </div>
      <div v-for="(item, index) in msgList" :key="index" @click="showActive(item)" class="item" :id="'A'+index">
        <div class="item-item" :class="[item.username ? 'tip-scroller__msg--active' : '']">
          <text class="" v-if="item.username">{{ item.username ? item.member_rank : '' }}</text>
          <text class="" v-if="item.username">{{ item.username ? item.rank : '' }}</text>

          <p class="username">
            <image class="tagimg" mode="widthFix" src="../../static/images/icon-newfans@3x.png"></image>{{ item.username ? item.username + ': ' : '' }}
          </p>

          <text class="" v-for="(text, i) in item.msg" :key="i"> {{ text }}</text>
        </div>

      </div>
    </scroll-view> -->
<!-- 	<scroll-view class="liveSayWrap" scroll-y="true" scroll-with-animation="true" @scroll="liveScroll" @scrolltolower="scrolltolower" :scroll-into-view="childrenId">
	  <div class="tipwrap">
	    {{ userInfo.system_notice }}
	  </div>
	  <div v-for="(item, index) in msgList" :key="index" class="item">
	    <div class="item-item" :class="[item.username ? 'tip-scroller__msg--active' : '']">
	      <text class="" v-if="item.username">{{ item.username ? item.member_rank : '' }}</text>
	      <text class="" v-if="item.username">{{ item.username ? item.rank : '' }}</text>
	      <p class="username">
	        <image class="tagimg" mode="widthFix" src="/static/images/icon-newfans@3x.png"></image>
	        <span  @click="liveRoomMonitoring(item)">  {{ item.username ? item.username + ': ' : '' }}</span>
	      </p>
	      <text class="" v-for="(text, i) in item.msg" :key="i"> {{ text }}</text>
	    </div>
	  </div>
	</scroll-view> -->
	<div class="tip" >
				<scroller class="tip-scroller">
				  <div class="tip-content">
					<text class="text">{{ userInfo.system_notice }}</text>
				  </div>
				  <div v-for="(item, index) in msgList" :key="index">
					<div class="tip-scroller__msg" :class="[item.username ? 'tip-scroller__msg--active' : '']">
					  <text class="tip-scroller__tag tip-scroller__member" v-if="item.username">{{ item.username ? item.member_rank : '' }}</text>
					  <text class="tip-scroller__tag" v-if="item.username">{{ item.username ? item.rank : '' }}</text>
					  <text class="tip-scroller__username"  @click="showActive(item)" >{{ item.username ? item.username + ': ' : '' }}</text>
					  <text class="tip-scroller__content">{{ item.msg }}</text>
					</div>
					<div :ref="'msg-' + index"></div>
				  </div>
				</scroller>
		</div>
    <div class="footerWrap">
      <div @click="switchCamera" class="buticon martp10">

        <u-icon name="/static/images/live/icon-transform.png"  color="#fff" size="58" label="翻转" label-pos="bottom" label-color="#fff"></u-icon>

      </div>
      <div class="buticon martp10" @click="snapshot">

        <u-icon name="/static/images/live/icon-screeShot.png" color="#fff" size="58" label="快照" label-pos="bottom" label-color="#fff"></u-icon>
      </div>
      <div class="buticon martp10" @click="startPusher">

        <u-icon :name="isPlay?'pause-circle':'play-circle'" :color="isPlay?'red':'#fff'" size="58" :label="isPlay?'暂停':'开播'" label-pos="bottom" label-color="#fff"></u-icon>
      </div>
      <div class="buticon martp10" @click="changewhiteness">
        <u-icon name="woman" color="'#fff" size="58" label="美白" label-pos="bottom" label-color="#fff"></u-icon>

      </div>
      <div class="buticon martp10" @click="beautiful">
        <u-icon name="woman" color="#fff" size="58" label="美颜" label-pos="bottom" label-color="#fff"></u-icon>

      </div>
    </div>
  </div>
</template>

<script>
var isFirst = false
var timer = null;
let client_id,token;
import {  
        mapState,  
        mapMutations  
    } from 'vuex';  

export default {
  data() {
    return {
      fil: true,
      pushUrl: '',
      isPlay: false,
      pushWidth: uni.getSystemInfoSync().windowWidth,
      pushHeight: uni.getSystemInfoSync().windowHeight,
      isLoading: false,
      currentWebview: null,
      pusher: null,
	  childrenId:"",
      toIndex: 'A6',
      coderate: '',
      context: null,
      whitenessLevel: 0,
      isBeautiful: 0,
      mode: [],
      msgList: [],
      userAvatarList: [],
      liveMessage:'',
      liveCode:'',


    }
  },

  onLoad() {
    client_id =  uni.getStorageSync('client_id')
    token = uni.getStorageSync('token')
 
    this.context = uni.createLivePusherContext("livePusher", this);
    uni.getStorage({
      key: 'pushUrl',
      success: res => {
        console.log("-> 直播推流地址res", res);
        this.pushUrl = res.data
      }
    })
    uni.setKeepScreenOn({
      keepScreenOn: true
    })
    this.context.startPreview(res => {
      console.log("-> ", '开启直播预览');
      console.log(res)
    })

    uni.getStorage({
      key: "openLiveID",
      success: res => {
        console.log("-> res", res);
        this.getAliveinformation(res.data)
      }
    })
  },
  onHide() {
  	this.logout()
  	console.log("离开页面----------------------------------------------------")
  },
	destroyed(){
		// console.log("离开页面")
		this.logout()
	},
	
  methods: {
	  go2bottom() {
	    const indicatorId = 'msg-' + (this.msgList.length - 1);
	    console.log("-> indicatorId", indicatorId);
	    const indicator = this.$refs[indicatorId];
	    console.log("-> indicator", indicator);
	      const el = indicator;
	      console.log("-> el", el);
	      dom.scrollToElement(el[0], {
	        offset: 300
	      });
	  
	  },
	  ...mapMutations(['logout']),
	  
	setScroll(){
		  let len = this.msgList.length;
		  // 我这里的id的设置规则是自己想的
		  // 只要不会重复 并且不事纯number就行
		  this.childrenId = 'id-'+(len-1); 
	  },
    getAliveinformation(e) {
      let data = {
        shop_id: e
      }
      this.$http.getAliveinformation(data).then(Res => {
        if (Res.status === 200) {
          console.log(Res)
          this.userInfo = Res.data;
          this.initWebSokcet(Res.data.room)
        }
      })
    },
    scroll(e) {
      console.log(e)

    },
    statechange(e) {
      console.log("statechange:" + JSON.stringify(e));
      this.liveMessage = e.detail.message;
      this.liveCode = e.detail.code
    },
    netstatus(e) {
      console.log('netstatus'+ JSON.stringify(e))
    },
    error(e) {
      console.log("error:" + JSON.stringify(e));
    },

    close: function () {
      this.context.close({
        success: (a) => {
          console.log("livePusher.close:" + JSON.stringify(a));
        }
      });
    },

    switchCamera() {
      this.context.switchCamera((a) => {
        console.log('livePusher.switchCamera:' + JSON.stringify(a))
      })
    },
    startPusher() {
  
        this.coderate = 'FHD'
        this.context.start(res=> {
          console.log("livePusher.start:" + JSON.stringify(res))
        })
        if (this.isPlay) {
          this.context.pause(res => {
            console.log("-> ", '直播已暂停');
            console.log(res)
          })
          this.coderate = ''
          this.isPlay = false
        } else {
          this.coderate = 'FHD'
          this.context.resume(res => {
            console.log("-> ", '直播已chong');
            console.log(res)
          })
          this.isPlay = true
        }
      },
  
    changewhiteness() {
      if (this.whitenessLevel) {
        this.whitenessLevel = 0
      } else {
        this.whitenessLevel = 5
      }
    },

    beautiful() {
      if (this.isBeautiful) {
        this.isBeautiful = 0
      } else {
        this.isBeautiful = 5
      }
    },
    snapshot() {
      this.context.snapshot({
        success: (e) => {
          console.log(JSON.stringify(e));
          console.log(e.tempImagePath)
          uni.saveImageToPhotosAlbum({
            filePath: e.tempImagePath,
            success: () => {
              console.log(e.tempImagePath)
              uni.showToast({
                title: '已保存快照到本地相册',

              });
            }
          });

        }
      });
    },
    resume() {
      this.context.resume({
        success: (a) => {
          console.log("livePusher.resume:" + JSON.stringify(a));
        }
      });
    },
    pause() {
      this.context.pause({
        success: (a) => {
          console.log("livePusher.pause:" + JSON.stringify(a));
        }
      });
    },
    stop() {
      this.context.stop({
        success: (a) => {
          console.log(JSON.stringify(a));
        }
      });
    },
    initWebSokcet(room) {
          uni.sendSocketMessage({
            data: JSON.stringify({
              type: 'bindalive_id',
              id:token,
              room,
              client_id
            })
          });
      uni.onSocketMessage(res => {
        const data = JSON.parse(res.data)
   
        if (data.type === 'alivesay') {
          console.log(data.data);
          this.msgList.push(data.data);
          this.$nextTick(() => {
            // this.toIndex = 'A' + this.msgList.length - 1
			this.$nextTick(() => {
			  setTimeout(() => {
			    this.go2bottom();
			  }, 50);
			});
            console.log(this.index)
          });
        }

        if (data.type === 'notice') {
          this.msgList.push({
            msg: data.msg
          });
          this.userAvatarList.unshift(data.data.headimgurl);
          this.$nextTick(() => {
            // this.toIndex = 'A' + this.msgList.length - 1
			this.$nextTick(() => {
			  setTimeout(() => {
			    this.go2bottom();
			  }, 50);
			});
            console.log(this.index)
          });
        }

      })

    },

  }
}
</script>

<style lang="scss" scoped>
	.tip-scroller__msg {
	  flex-direction: row;
	  flex-wrap: wrap;
	  align-items: center;
	  margin-bottom: 8upx;
	  border-radius: 100upx;
	  padding: 2upx 6upx;
	  width: 750upx;
	
	}
	.tip-scroller__username {
	  color: rgba(255, 143, 45, 1);
	  font-size: 24upx;
	
	}
	
	.tip-scroller__content {
	  color: #fff;
	  font-size: 22upx;
	  background-color: rgba(0,0,0,0.5);
	  border-radius: 100px;
	  padding:0 14upx;
	  height: 34upx;
	  line-height: 34upx;
	}
	.tip-scroller__tag {
	
	  padding: 2upx 6upx;
	  margin-right: 6upx;
	  font-size: 20upx;
	  text-align: center;
	  color: #fff;
	  border-radius: 200px;
	  background-image:linear-gradient(to right, #ff6f0f, #fa3e3f);
	}
	
	.tip-scroller__member {
	  border-radius: 200px;
	  background-image: linear-gradient(to right, #ff9900, #ffaf37);
	}
	
	.tip {
	  position: fixed;
	  bottom: 240upx;
	  left: 24upx;
	}
	
	.tip-content {
	  width: 600upx;
	  height: 140upx;
	  font-size: 13upx;
	  padding: 15upx;
	  margin-bottom: 12upx;
	  background-color: rgba(0, 0, 0, 0.4);
	  border-radius: 18upx;
	  color: #ff8534;
	}
	
	.tip-scroller {
	  height: 420upx;
	}
	
.livePusher {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

.footerWrap {
  position: fixed;
  bottom: 50upx;

  display: flex;
  width: 100%;
  z-index: 1000;
  justify-content: space-between;

  .buticon {
    text-align: center;
    width: 25%;
    color: #fff;

    .buticon-img {
      width: 60upx;
    }
  }

}

.liveSayWrap {
  position: fixed;
  bottom: 150upx;
  left: 20upx;
  width: 500upx;
  overflow: hidden;
  height: 380upx;
  font-size: 24upx;
}

.tipwrap {
  @extend .item;
  color: #ff8534;
  border-radius: 8upx!important;
}
.tagimg {
  width: 50upx;
  margin: 0 8upx;
}
view {
  font-size: 24upx;
}

.item {
  background-color: rgba(#000, 0.2);
  color: #FFF;
  padding: 2upx 10upx;
  border-radius: 10upx;
  font-size: 24upx;
  margin-bottom: 10upx;

  &-item {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
}

.username {
  color: #ff8534
}
.pusherNetStatus{
  position:fixed;
  top: 100upx;
  right: 30upx;
  background-color: rgba(#000,0.5);
  border-radius:4upx;
  color: #eee;
  font-size: 20upx;
}
</style>
